# -*- coding: UTF-8 -*
# !/usr/bin/python3
import requests
from bs4 import BeautifulSoup
import PyRSS2Gen
import datetime
import os
import random


def getRssPath():
    abspath = os.getcwd()  # 获取当前路径
    p = abspath.replace(abspath.split("/")[-1], "rss")
    return p


def get_header():
    header1 = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0"
    }
    header2 = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362"
    }
    header3 = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"
    }
    header_list = [header1, header2, header3]
    index = random.randint(0, 1)
    return header_list[index]
    pass


def WeiboHot():
    headers = get_header()
    print('WeiboHot-startTime:%s' %
          (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
    hot_url = 'https://s.weibo.com/top/summary/'
    event_url = 'https://s.weibo.com/top/summary/summary?cate=socialevent'
    r = requests.get(url=hot_url, headers=headers)
    soup = BeautifulSoup(r.text, 'lxml')
    urls_titles = soup.select(
        '#pl_top_realtimehot > table > tbody > tr > td.td-02 > a')
    item = []
    # for i in range(len(urls_titles)-1):
    #     hot_news = PyRSS2Gen.RSSItem(
    #         title = urls_titles[i+1].get_text(),
    #         description = urls_titles[i+1].get_text().encode("utf-8"),
    #         link = "https://s.weibo.com"+urls_titles[i]['href'],
    #     )
    #     item.append(hot_news)
    hots = ''
    for i in range(len(urls_titles)-1):
        hots += "<p>"+str(i+1)+" - " + urls_titles[i+1].get_text() + "</p>"

    r1 = requests.get(url=event_url, headers=headers)
    soup1 = BeautifulSoup(r1.text, 'lxml')
    div_content = soup1.find_all("tr", class_="")
    t = 1
    evs = ''
    i = 0
    for item in div_content:
        if (t == 1):
            t = 0
            continue
        content = item.select("td")[1].select("a")[0].string
        evs += "<p>"+str(i+1)+" - " + content + "</p>"
        i = i+1
    nowtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    item = [
        PyRSS2Gen.RSSItem(
            title=str(nowtime)+" 新浪热搜",
            description=hots,
            link='',
        ),
        PyRSS2Gen.RSSItem(
            title=str(nowtime)+" 新浪关键词",
            description=evs,
            link=''
        ),
    ]
    rss = PyRSS2Gen.RSS2(
        title='新浪微博',
        link='https://s.weibo.com/top/summary/',
        description='新浪微博',
        items=item
    )
    rss_path = getRssPath()
    if not os.path.exists(rss_path):
        os.mkdir(rss_path)
    rss.write_xml(open(rss_path+"/"+WeiboHot.__name__ +
                  ".xml", "w"), encoding="utf-8")
    print('WeiboHot-endTime:%s' %
          (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
    print('------------------------------------------------------------------------')


if __name__ == '__main__':
    # 30min weibohot news title
    WeiboHot()
